package com.baichang.taoshunda.dao.impl;

import com.baichang.framework.dao.impl.BaseDaoImpl;
import com.baichang.taoshunda.dao.PromotionDao;
import com.baichang.taoshunda.entity.Promotion;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by ${wushenglu} on 17/08/23.
 */
@Repository
public class PromotionDaoImpl extends BaseDaoImpl<Promotion> implements PromotionDao {

    /**
     * 查询每个商家的优惠活动
     *
     * @param busId 商家编号
     * @return
     */
    @Override
    public List<Map<String, Object>> getPromotionByBussId(int busId) {
        String sql = "SELECT * FROM t_promotion WHERE buss_id=? AND TO_DAYS(start_time)<=TO_DAYS(NOW()) AND TO_DAYS(end_time)>=TO_DAYS(NOW());";
        return queryForMapList(sql, busId);
    }

    /**
     * 查看优惠活动
     *
     * @param id
     * @return
     */
    @Override
    public List<Map<String, Object>> examineActivity(Integer id) {
        String sql = "SELECT * FROM t_promotion WHERE buss_id=?";
        return queryForMapList(sql, id);
    }

    @Override
    public int getPromotionCountByBussId(int busId) {
        String sql = "SELECT COUNT(0) FROM t_promotion WHERE buss_id=? " +
                "AND TO_DAYS(start_time)<=TO_DAYS(NOW()) AND TO_DAYS(end_time)>=TO_DAYS(NOW())";
        return queryForInt(sql, busId);
    }

    @Override
    public int updateBusinessActivity(Integer id, String name) {
        String sql = "UPDATE {table} SET name=? WHERE id=?";
        return update(sql, name, id);
    }

    /**
     * 根据状态查询商家的活动
     *
     * @param bussId 商家编号
     * @param state  状态
     *               0：待生效
     *               1：已生效
     *               2：已结束
     * @return
     */
    @Override
    public List<Map<String, Object>> findPromotionByState(Integer bussId, Integer state) {
        String sql = " SELECT *," + state + " state FROM ( " +
                "SELECT id,group_concat(`name` Separator ';') as name,buss_id bussId,min_money,sub_money,created,start_time startTime,receive_end_time endTime,validity_days validityDays,1 type,coupon_kid kid FROM t_coupon  GROUP BY kid  " +
                "UNION ALL " +
                "SELECT id,name,buss_id bussId,min_money,sub_money,created,start_time startTime,end_time endTime,0 validityDays,2 type,0 kid FROM t_promotion " +
                ") AS newTable WHERE newTable.bussId=? ";
        List<Object> objs = new ArrayList<Object>();
        objs.add(bussId);
        if (state == 0) {
            sql += "  AND CURDATE()<newTable.startTime ";
        } else if (state == 1) {
            sql += " AND CURDATE()>=newTable.startTime AND CURDATE()<=newTable.endTime  ";
        } else if (state == 2) {
            sql += " AND CURDATE()>newTable.endTime ";
        }
        sql += " ORDER BY newTable.created DESC ";
        return queryForMapList(sql, objs.toArray());
    }
}
